<script setup>
import { ref, onMounted, watch } from 'vue'

const canvas = ref(null)
let context = null

let startPos = ref({
    x: -1,
    y: -1
})

let endPos = ref({
    x: -1,
    y: -1
})

let lining = false

onMounted(() => {
    context = canvas.value.getContext('2d')

    context.lineWidth = 1
    context.lineCap = 'butt'
    context.lineJoin = 'miter'
})

const draw = (startX, startY, endX, endY) => {
    // 清理画布
    context.clearRect(0, 0, canvas.value.width, canvas.value.height)

    // 算斜率
    let distanceX = endX - startX
    let distanceY = endY - startY
    let distance = Math.sqrt(distanceY * distanceY + distanceX * distanceX)

    // 箭头的尺寸
    let distanceArrow = 7
    let sharpeArrow = 3

    let arrowLineTo = {
        x: endX - distanceArrow * distanceX / distance,
        y: endY - distanceArrow * distanceY / distance
    }

    let arrowTo3 = {
        x: arrowLineTo.x - sharpeArrow * distanceY / distance,
        y: arrowLineTo.y + sharpeArrow * distanceX / distance
    }

    let arrowTo4 = {
        x: arrowLineTo.x + sharpeArrow * distanceY / distance,
        y: arrowLineTo.y - sharpeArrow * distanceX / distance
    }

    context.beginPath()
    context.moveTo(startX, startY)
    context.lineTo(endX, endY)
    context.lineTo(arrowTo3.x, arrowTo3.y)
    context.lineTo(arrowTo4.x, arrowTo4.y)
    context.lineTo(endX, endY)
    context.closePath()
    context.stroke()
    context.fill()
}

const onCanvasClick = (evt) => {
    if (lining === false) {
        lining = true
        endPos.value.x = -1
        endPos.value.y = -1

        startPos.value.x = evt.offsetX
        startPos.value.y = evt.offsetY
    } else {
        lining = false
        endPos.value.x = evt.offsetX
        endPos.value.y = evt.offsetY
    }
}

const onCanvasMouseMove = (evt) => {
    if (lining === true) {
        endPos.value.x = evt.offsetX
        endPos.value.y = evt.offsetY
    }
}

watch([() => startPos.value, () => endPos.value], () => {
    if (startPos.value.x > -1 && endPos.value.x > -1) {
        draw(startPos.value.x, startPos.value.y, endPos.value.x, endPos.value.y)
    }
}, { deep: true })
</script>

<template>
    <div class="wrapper">
        <div>
            <canvas @click="onCanvasClick" @mousemove="onCanvasMouseMove" ref="canvas" width="500" height="500" style="border: 1px solid #ccc;"></canvas>
        </div>
    </div>
</template>

<style scoped>
.wrapper {
    position: relative;
    height: 100%;
    padding: 8px;
    overflow: auto;
}
</style>